package com.fjwt.gz.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjwt.gz.core.constants.Constants;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.utils.SpringBeansUtil;
import com.fjwt.gz.db.dto.ACTE027StatDTO;
import com.fjwt.gz.db.dto.OldFansInfoDTO;
import com.fjwt.gz.db.dto.ScoreRecordDTO;
import com.fjwt.gz.db.entity.*;
import com.fjwt.gz.db.vo.ACTE027StatVO;
import com.fjwt.gz.interfaces.BaseScoreRecodService;
import com.fjwt.gz.service.mapper.OldFansInfoMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
@Slf4j
public class OldFansInfoService extends ServiceImpl<OldFansInfoMapper, OldFansInfoEntity> {
    @Autowired
    private ScoreTotalService scoreTotalService;
    @Autowired
    private ScoreRecordTotalService scoreRecordTotalService;
    @Autowired
    private OldFansInfoMapper oldFansInfoMapper;

    // TODO 历史积分数据迁移待完成
    @Transactional(rollbackFor = Exception.class)
    public void oldScoreMove(OldFansInfoEntity old, Long agentScoreId, Long fansId, String appId) {
        log.info("迁移福分定时任务：{},用户id：{}", JSONObject.toJSONString(old),fansId);
        ScoreTotalEntity totalEntity = scoreTotalService.selectByFansId(fansId, appId);
        log.info("客户总福分：{}",JSONObject.toJSONString(totalEntity));
        long fansNum = fansId % 8;
        log.info("{}客户fansId，历史福分迁移，分表处理的：{}",fansId,fansNum);
        // TODO 历史福分迁移进行对应的库表操作
        if(null == totalEntity){
            // 用户总积分
            ScoreTotalEntity dto = new ScoreTotalEntity();
            dto.setCreatedAt(new Date());
            dto.setCurrentScore(old.getScore());
            dto.setFansId(fansId);
            dto.setAppId(appId);
            dto.setAgentScoreId(agentScoreId);
            scoreTotalService.save(dto);
        }else{
            int score = old.getScore()+totalEntity.getCurrentScore();
            totalEntity.setCurrentScore(score);
            scoreTotalService.updateById(totalEntity);
        }
        Date dataTime = new Date();
        ScoreRecordTotalEntity recordTotalEntity = new ScoreRecordTotalEntity();
        recordTotalEntity.setFansId(fansId);
        recordTotalEntity.setCreatedAt(dataTime);
        recordTotalEntity.setScore(old.getScore());
        recordTotalEntity.setName("历史福分迁移");
        recordTotalEntity.setAgentScoreId(agentScoreId);
        recordTotalEntity.setFlag(Constants.FANS_AWARD_STATE.UNUSED);
        String str  = fansId+"_"+"NULL"+"_"+"NULL"+ DateUtil.format(dataTime, DatePattern.PURE_DATE_PATTERN);
        recordTotalEntity.setUniqueKey(str);
        scoreRecordTotalService.save(recordTotalEntity);
        log.info("历史福分迁移记录：{}",JSONObject.toJSONString(recordTotalEntity));

        BaseScoreRecodService scoreRecordService = SpringBeansUtil.getBean("scoreRecord0" + fansNum + "Service", BaseScoreRecodService.class);
        if (ObjectUtil.isNull(scoreRecordService)) {
           throw new BizException("历史福分迁移,接口不存在");
        }
        List<ScoreRecordDTO> list = new ArrayList<>();
        for(int i=0;i<old.getScore();i++){
            // 增加用户积分记录
            ScoreRecordDTO scoreRecordDTO = new ScoreRecordDTO();
            scoreRecordDTO.setFansId(fansId);
            scoreRecordDTO.setState(Constants.FANS_AWARD_STATE.UNUSED);
            scoreRecordDTO.setCreatedAt(new Date());
            scoreRecordDTO.setScoreAddId(recordTotalEntity.getScoreRecordTotalId());
            scoreRecordDTO.setRemark("历史福分迁移");
            scoreRecordDTO.setAgentScoreId(agentScoreId);
            try{
                scoreRecordDTO.setOverTime(DateUtil.offsetDay(new Date(), 59));
            }catch (Exception e){
                log.info("设置过期时间转换异常！");
                log.info("积分参数信息：{},用户fansId:{}", JSONObject.toJSONString(old),fansId);
            }
            list.add(scoreRecordDTO);
            if (list.size()>0 && list.size() == 2000){
                scoreRecordService.addScore(list);
                list.clear();
            }
        }
        if(list.size()>0){
            scoreRecordService.addScore(list);
        }
        old.setFansId(fansId);
        old.setState(0);
        old.setSyncTime(new Date());
        log.info("更改数据信息：{}",JSONObject.toJSONString(old));
        oldFansInfoMapper.updateById(old);
    }

    /**
     * 根据openId 查询存量数据（获取实名认证数据）
     * @param openid
     * @return
     */
    public OldFansInfoEntity selectOldFansInfoByOpenId(String openid) {
        return oldFansInfoMapper.selectOneByOpenId(openid);
    }

    public IPage<OldFansInfoDTO> selectOldFansInfoByDTO(IPage page, OldFansInfoDTO dto) {
        return oldFansInfoMapper.selectOldFansInfoByDTO(page,dto);
    }

    public List<OldFansInfoDTO> selectOldFansInfoByDTOList(OldFansInfoDTO dto) {
        return oldFansInfoMapper.selectOldFansInfoByDTOList(dto);
    }


    /**
     * 获取分页列表
     * @param iPage
     * @param acte027StatDTO
     * @return
     */
    public IPage<OldFansInfoEntity> getDetails(IPage iPage, ACTE027StatDTO acte027StatDTO) {
        LambdaQueryWrapper<OldFansInfoEntity> gw = OldFansInfoEntity.gw()
                .isNotNull(OldFansInfoEntity::getSyncActivityId)
                .lt(OldFansInfoEntity::getSyncTime, DateUtil.beginOfDay(DateUtil.date()))
                .eq(ObjectUtils.isNotEmpty(acte027StatDTO.getFansId()), OldFansInfoEntity::getFansId, acte027StatDTO.getFansId())
                .eq(ObjectUtils.isNotEmpty(acte027StatDTO.getPhone()), OldFansInfoEntity::getPhone, acte027StatDTO.getPhone())
                .in(ObjectUtils.isNotEmpty(acte027StatDTO.getAgentNoList()), OldFansInfoEntity::getAgentNo, acte027StatDTO.getAgentNoList());

        gw.select(OldFansInfoEntity::getFansId, OldFansInfoEntity::getRealName, OldFansInfoEntity::getPhone, OldFansInfoEntity::getNewAgentNo4,
                OldFansInfoEntity::getNewAgentName4, OldFansInfoEntity::getNewAgentNo3, OldFansInfoEntity::getNewAgentName3);

        return oldFansInfoMapper.selectPage(iPage, gw);
    }

    /**
     * 福利焕活领取明细导出
     * @param acte027StatDTO
     * @return
     */
    public List<ACTE027StatVO> getActe027Export(ACTE027StatDTO acte027StatDTO) {
        return oldFansInfoMapper.getActe027Export(acte027StatDTO);
    }
}
